package io.github.lee.app.unsplash.ui.search.result.photo

import android.app.Application
import com.chad.library.adapter.base.BaseQuickAdapter
import dagger.hilt.android.lifecycle.HiltViewModel
import io.github.lee.app.unsplash.repository.SearchRepository
import io.github.lee.app.unsplash.repository.domain.Photo
import io.github.lee.app.unsplash.ui.main.home.page.TopicPhotoAdapter
import io.github.lee.core.vm.BaseRefreshViewModel
import javax.inject.Inject

@HiltViewModel
class ResultPhotoVM @Inject constructor(
    application: Application,
    private val repo: SearchRepository
) : BaseRefreshViewModel<Photo>(application) {
    var searchKeyword: String = ""

    override fun onCreateAdapter(): BaseQuickAdapter<Photo, *> =
        TopicPhotoAdapter()


    //===Desc:======================================================================================

    override fun onRefreshOrLoadMore(isRefresh: Boolean) {
        super.onRefreshOrLoadMore(isRefresh)
        if (isRefresh) currentPage = 1 else currentPage++
        launchResult({
            repo.searchPhoto(searchKeyword, currentPage)
        }, { error() }) {
            if (!it.isSuccess()) {
                error()
                if (isRefresh) refreshFail() else loadMoreFail()
                return@launchResult
            }
            val data = it.data
            if (null == data) {
                error()
                if (isRefresh) refreshFail() else loadMoreFail()
                return@launchResult

            }
            val results = data.results
            if (results.isNullOrEmpty()) {
                if (isRefresh) refreshSuccess() else loadMoreSuccess(false)
                return@launchResult
            }

            if (isRefresh) {
                submitList(results)
                refreshSuccess()
            } else {
                addAll(results)
                loadMoreSuccess(currentPage <= data.total)
            }


        }


    }


}